/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package android.reasons;

import android.app.Activity;
import android.app.ContextoAndroid;
import android.app.Mensaje;
import android.app.ProgressDialog;
import android.app.PromptDialog;
import android.web.async.WebAmigos;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.web.service.WebService;
import android.widget.LinearLayout;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ProgressBar;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

/**
 *
 * @author efraingutierrez
 */
public class Publicar extends Activity implements OnClickListener,OnTouchListener
{ 
    private LinearLayout abs;
    private EditText etAmigo;
    private ProgressBar pb;
    private ListView lvAmigos;
    private ImageView imgSearch;
    private WebAmigos webAmigos;
    private String IdPublicar = "";
    private GestureDetector gestureDetector;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        ContextoAndroid.context = this;
        gestureDetector = new GestureDetector(this, new GestureListener());
        this.setContentView(R.layout.publicar);
        abs = (LinearLayout)this.findViewById(R.id.absPublish);
        abs.setBackgroundResource(R.drawable.turquesa);
        imgSearch = (ImageView)this.findViewById(R.id.imgPubli);
        imgSearch.setOnClickListener(this);
        etAmigo = (EditText)this.findViewById(R.id.etBuscarAmigos);
        lvAmigos = (ListView)this.findViewById(R.id.lvAmigos);
        Typeface font = Typeface.createFromAsset(getAssets(), "abril.ttf");
        for (int i = 0; i < abs.getChildCount(); i++) 
        {
            View v = abs.getChildAt(i);
            if (v instanceof EditText) 
            {
                ((EditText)v).setTypeface(font);
            } else if (v instanceof TextView) {
                ((TextView)v).setTypeface(font);
            } 
        }
        pb = (ProgressBar)this.findViewById(R.id.progReason);
        pb.setVisibility(ProgressBar.GONE);
       
        this.lvAmigos.setOnTouchListener(this);
    }
   
    public void onClick(View arg0) 
    {  
        if(arg0.getTag().equals("img"))
        {
            if(validar())
            {
                webAmigos = new WebAmigos(lvAmigos);
                webAmigos.execute(etAmigo.getText().toString());
            }
        }
    }
    
    private Boolean validar()
    {
        String tiempo = etAmigo.getText().toString(); 
        if(tiempo.equals(""))
        {
            Mensaje.Mostrar("El Valor del campo de texto no puede estar vacìo");
            return false;
        }
        return true;
    }
    
    private void clear()
    {
        IdPublicar = "";
        Mensaje.Mostrar("Se Ha Publicado el Mensaje");
    }
    
  

    public boolean onTouch(View arg0, MotionEvent arg1) {
        //Single Tap
        ListView l = (ListView)arg0;
        int adapterIndex = l.pointToPosition((int) arg1.getX(),(int) arg1.getY());
        if(adapterIndex>=0)
        {
            IdPublicar = webAmigos.getRowItems().get(adapterIndex).getDesc();
            return gestureDetector.onTouchEvent(arg1);
        }
        else return super.onTouchEvent(arg1);
    }
    
     private class WebPetition extends AsyncTask<String, Integer, Boolean> {
        
        ProgressDialog dialog;
        
        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(ContextoAndroid.context);
            dialog.setIndeterminate(false);
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setCancelable(true);
            dialog.setMessage("Publicando...");
            dialog.show();
        }
        @Override
        protected Boolean doInBackground(String... params) 
        {
            ArrayList<NameValuePair> lst = new ArrayList<NameValuePair>();
            lst.add(new BasicNameValuePair("pensamiento",params[0]));
            lst.add(new BasicNameValuePair("idreceptor",params[1]));
            lst.add(new BasicNameValuePair("idremitente",params[2]));
            WebService.HttpPost(lst, "Controladores/nuevaRazon.php");
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) 
        {
            dialog.dismiss();
            if(result)
            {
                Mensaje.Mostrar("Publicación Exitosa");
            }
            else Mensaje.Mostrar("Ha Ocurrido un Error...");
        }
        @Override
        protected void onProgressUpdate(Integer... values) 
        {
            dialog.setMessage("Publicando...");
            dialog.setProgress(values[0]);
        }
    }
     private class GestureListener extends GestureDetector.SimpleOnGestureListener {

            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }
            // event when double tap occurs
            @Override
            public boolean onDoubleTap(MotionEvent e) {
                if(!IdPublicar.equals(""))
                    {
                        PromptDialog dlg = new PromptDialog(ContextoAndroid.context, R.string.title, R.string.crear) {
                            @Override
                            public boolean onOkClicked(String input) 
                            {
                                if(!input.equals(""))
                                {
                                    new WebPetition().execute(input,IdPublicar,ContextoAndroid.usuario.correo);
                                    clear();
                                    return true;
                                }
                                else 
                                {
                                    Mensaje.Mostrar("Debe Introducir Una Razón");
                                    return false;
                                }
                            }
                        };
                        dlg.show();  
                    }
                    else Mensaje.Mostrar("No Ha Seleccionado un Amigo...");

                return true;
         }
    }
}

